<?php
namespace app\services;

class CampaignLabelService extends BaseService {
    public $matrix = [
        'id' => 'id',
        'name' => 'name',
        'advertiser' => 'advertiser',
        'status' => ['status', '$v==1&&$v="active";
                                $v==2&&$v="inactive";
                                return $v;'],
        'launchNum' => 'campaignCount',
        'comment' => 'description',
        'modifiedDate' => 'last_update',
        'operate' => ['id', 'return "edit, view";'],
    ];

    public function saveNewLabel($post) {
        $data['id'] = $post['id'];
        $_POST['name'] = $this->dropBlank($post['name']);
        $data['name'] = $post['name'];
        $data['description'] = $post['description'];
        !$data['id'] && $data['advertiser_id'] = $this->S('advertiser_id');
        $isNew = $this->save('CampaignLabel', $data);
        if ($isNew) {
            $data = $isNew;
        }
        return $data;
    }

    public function getAllLabels() {
        $where = [];
        $aIds = $this->getAIds();
        if (!$aIds) return [];
        $where = " advertiser_id in $aIds and status > 0 ";
        $campaigns = $this->getAll('Campaign', $where);
        $campaigns = $this->arrayGroup($campaigns, 'label_id');
        $labels = $this->getAll('CampaignLabel', $where);
        $advertisers = $this->getAll('Advertiser');

        foreach ($labels as &$label) {
            $label['campaignCount'] = 0;
            if (in_array($label['id'], array_keys($campaigns))) {
                $label['campaignCount'] = count($campaigns[$label['id']]);
            }
            if (in_array($label['advertiser_id'], array_keys($advertisers))) {
                $label['advertiser'] = $advertisers[$label['advertiser_id']]['name'];
            }
        }
        return $this->fieldsMap($this->matrix, $labels);
    }

}//end

